package com.borened.common.core.util;

import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * <p>
 * 字符串模板解析工具类
 * </p>
 *
 * @author wqx
 * @since 2022-07-07
 */
public class StringUtils {
    /**
     * 解析预定长度的模板字符串并解析对应`{}`参数
     * <p>
     * 例如传入的 原始字符串sourceMsg： a111b222c333d444
     * 占位模板template:    x{a:3}x{b:3}x{c:4}x{d:3}
     * 解析结果: {a:111,b:222,c:333,d:444}
     * </p>
     *
     * @param sourceMsg 源消息
     * @param template  模板表达式
     * @return key-value 参数合集
     */
    public static Map<String, String> parseTemplate2Map(String sourceMsg, String template) {
        int i = 0;
        Map<String, String> result = new HashMap<>();
        String regex = "(\\{([^}])*})";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(template);
        //预检查
        if (!matcher.find()) {
            throw new IllegalArgumentException("不支持的模板表达式！必须使用{param:4}的形式");
        }
        matcher.reset();
        while (matcher.find()) {
            String group = matcher.group();
            int start = matcher.start();
            String[] split = group.split(":");
            String name = split[0].replace("{", "");
            int len = Integer.parseInt(split[1].replace("}", ""));
            start = start + i;
            int end = start + len;
            //越界检查
            if (end > sourceMsg.length()) {
                end = sourceMsg.length();
            }
            String value = sourceMsg.substring(start, end);
            i = i + len;
            template = template.replace(group, "");
            matcher = pattern.matcher(template);
            result.put(name, value);
        }
        return result;
    }

    public static void main(String[] args) {
        Map<String, String> map = parseTemplate2Map("a111b222c333d444", "x{a:3}x{b:3}x{c:3}x{d:3}");
        System.out.println(map);
    }
}
